#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"userMysql.h"
#include "usermysqls.h"
#include"logrecord.h"
#include"maininterface.h"
Q_GLOBAL_STATIC(MainWindow,theInstance);
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{

    connectMySql();
    ui->setupUi(this);
    //给登录页面设置背景图片
    this->setWindowTitle("登录界面");
    this->setWindowIcon(QIcon(":res/res/Log_In.ico"));
    setFixedSize(QSize(1800,940));//设置qt登录页面的大小
  //  "   background-size: cover;"                        // 自适应填充

    this->setStyleSheet(
        "MainWindow {"
        "   background-image: url(:/res/res/1.jfif);" // 资源路径
        "   background-position: center;"                   // 居中
        "   background-repeat: no-repeat;"                  // 不重复
        "   background-attachment: fixed;"                  // 固定不滚动

        "}"

        "QLabel, QPushButton {"
        "   background: white;"                       // 子控件为白色
        "}"

    );

//transparent//透明
    //将标题居中
//    int titleWidth=ui->Pushbutton_title->width();
//    int titleHeight=ui->Pushbutton_title->height();
//    int x=(1800-titleWidth)/2;
//    //int y=(940-titleHeight)/2;
//    ui->Pushbutton_title->setGeometry(x,0,titleWidth,titleHeight);
//    //将标题字体颜色改为 黑色
//     ui->Pushbutton_title->setStyleSheet("color: black;");
     //将竖直布局放在ui中间
     //输入密码
    //限制输入密码数数位
     // 创建一个正则表达式，限制输入为 6 位数字
     QRegExp regExp("\\d{6}");
     QRegExp regExpA("\\d{11}");
     QRegExpValidator *validator = new QRegExpValidator(regExp, this);
     QRegExpValidator *validatorA = new QRegExpValidator(regExpA, this);
     ui->lineEdit_Password->setValidator(validator);
     ui->lineEdit_AccountNumber->setValidator(validatorA);

     //设置输入框的显示模式为密码模式
     ui->lineEdit_Password->setEchoMode(QLineEdit::Password);
//     initUserType();//初始化登录类型按键
       initUserTypeS();
connect(RegisteredUserInformation::instance(),&RegisteredUserInformation::RegisterUser,this,&MainWindow::connectMySql,Qt::QueuedConnection);//更新user用户信息


}

MainWindow::~MainWindow()
{
    delete ui;
}

MainWindow *MainWindow::instance()
{
    return theInstance;
}

void MainWindow::QStringUserType(bool userType, QString &qstringUserType)
{
userType?qstringUserType="管理员":qstringUserType="普通用户";
}

void MainWindow::connectMySql()
{
    //userMysql::instance()->getUserData(users);
    UserMysqlS::instance()->getUserData(users);
    UserMysqlS::instance()->getPidSetPointValue();
    UserMysqlS::instance()->getSensorWarningTimes();//从数据库获取报警次数
    UserMysqlS::instance()->getTimeCycleSets();//从数据中获取各时间设置的值

//    int count=users.count();
//    qDebug()<<"count:"<<count;
//    for(QVector<UserInfo>::iterator it=users.begin();it!=users.end();it++)
//    {
//        qDebug()<<it->userName<<" "<<it->userType<<" "<<it->userPassword<<endl;
//    }

}

void MainWindow::LineEditPassword()
{
    //bool ok=ui->pushButtonAdmin->isChecked();
    bool ok=userType;
    qDebug()<<ok;
    //    if(ok)
    //    {
    //        userType=1;
    //    }
    //    else{
    //        userType=0;

    //    }

    bool accountNumberFlag=false;
    bool userNameFlag=false;
    bool userTypeFlag=false;
    bool passwordFlag=false;
    qDebug()<<userType;
    bool currentUserType=false;
    QString accountNumberText=ui->lineEdit_AccountNumber->text();
    QString userNameText=ui->lineEdit_UserName->text();
    QString passwordText=ui->lineEdit_Password->text();
    qDebug()<<passwordText;
    QString qstringUserType;
    QStringUserType(userType,qstringUserType);
    for(QVector<UserInfo>::iterator it=users.begin();it!=users.end();it++)
    {
        if(accountNumberText==it->accountNumber)//寻找用户是否存在
        {
            accountNumberFlag=true;
            qDebug()<<"验证账号成功";
            if(it->userType==userType)//验证用户类型
            {
                userTypeFlag=true;
                qDebug()<<userType<<"->"<<it->userType;
                currentUserType=it->userType;
                qDebug()<<"验证用户类型成功";


            }
            if(userNameText==it->userName)//验证用户名
            {
                userNameFlag=true;
                qDebug()<<"验证用户名成功";



            }
            if(it->userPassword==passwordText)
            {
                passwordFlag=true;
                qDebug()<<"验证密码成功";

            }
            if(accountNumberFlag)break;



        }

    }

    if(!accountNumberFlag)
    {

        QMessageBox::StandardButton reply = QMessageBox::warning(
                    this,
                    "账户不存在",
                    "请检查账号是否正确！",
                    QMessageBox::Yes |QMessageBox::Cancel
                    );

        if (reply == QMessageBox::Yes)
        {
            ui->lineEdit_AccountNumber->clear();
        }
      LogRecord::instance()->writeLogRecord("该账号不存在!");


    }
    else if(!userNameFlag)
    {
        QMessageBox::StandardButton reply = QMessageBox::warning(
                    this,
                    "用户名不存在",
                    "请检查用户名是否正确！",
                    QMessageBox::Yes |QMessageBox::Cancel
                    );
    LogRecord::instance()->writeLogRecord("该用户名不匹配!");

    }
    else if(!userTypeFlag)
    {
        QMessageBox::StandardButton reply = QMessageBox::warning(
                    this,
                    "用户类型不匹配",
                    "请检查用户类型！",
                    QMessageBox::Yes |QMessageBox::Cancel
                    );
   LogRecord::instance()->writeLogRecord("该用户类型不匹配!");

    }
    else if(!passwordFlag)
    {
    qDebug()<<"输入密码失败，请重新输入密码！"<<endl;
    QMessageBox::StandardButton reply = QMessageBox::question(
                this,
                "密码错误",
                "请检查密码",
                QMessageBox::Yes | QMessageBox::No
                );
     LogRecord::instance()->writeLogRecord("该密码不匹配!");

//    if (reply == QMessageBox::Yes) {
//        // 用户点击了“是”
//    } else {
//    // 用户点击了“否”
//    }
    //ui->lineEdit_Password->clear();
    }
    if(accountNumberFlag&&userTypeFlag&&userNameFlag&&passwordFlag)
    {
    extern QString currentUserName;

    extern UserInfo currentUserInfo;//存储当前用户信息
    currentUserInfo.accountNumber=accountNumberText;
    currentUserInfo.userName=userNameText;
    currentUserInfo.userPassword=passwordText;
    currentUserInfo.userType=currentUserType;
    currentUserName=userNameText;
        if(userType)
        {
            qDebug()<<"管理员用户";
            QMessageBox msgBox;
            msgBox.setStandardButtons(QMessageBox::Yes );
            msgBox.setWindowTitle("Tip");
            msgBox.setText("登录管理员账户！");
            msgBox.button(QMessageBox::Yes)->setText("确定");
            msgBox.exec();
            openMainInterface();
            return;

        }
        else{
            QMessageBox msgBox;
            msgBox.setStandardButtons(QMessageBox::Yes );
            msgBox.setWindowTitle("Tip");
            msgBox.setText("登录普通账户！");
            msgBox.button(QMessageBox::Yes)->setText("确定");
            msgBox.exec();
            qDebug()<<"普通用户";

            openMainInterface();
            return;
        }




    }



}


//--------------------------------------------------------------------
// bool flag=0;
//for(QVector<UserInfo>::iterator it=users.begin();it!=users.end();it++)
//{

//    if(passwordText==it->userPassword)
//    {
//        qDebug()<<"输入密码正确！"<<endl;
//        flag=1;
//        openMainInterface();


//        break;
//    }

//}
//if(flag==0)
//{
//    qDebug()<<"输入密码失败，请重新输入密码！"<<endl;
//    ui->lineEdit_Password->clear();

//}




void MainWindow::openMainInterface()
{

//    MainInterface *view=new MainInterface(this);
     this->hide();//隐藏当前界面
    //connect(view, &MainInterface::returnToParentSignal,this , &MainWindow::reshowMainWindow); // 连接返回信号
//    view->show();
extern UserInfo currentUserInfo;//存储当前用户信息
QString UserType;
//if(currentUserInfo.userType)
//{
//    UserType="管理员";
//}
//else{
//UserType="普通用户";
//}
QStringUserType(currentUserInfo.userType,UserType);
//currentUserInfo.userType ? UserType="管理员":UserType="普通用户";
LogRecord::instance()->writeLogRecord("登录系统成功!",currentUserInfo.userName,UserType);
MainInterface::instance()->show();
emit sendUpDateUserInformation();
qDebug()<<"显示主页面";


}

void MainWindow::initUserTypeS()
{
ui->radioButtonAdmin->setCheckable(true);
ui->radioButtonUser->setCheckable(true);
}

//void MainWindow::initUserType()
//{
////设置两按钮为可选中状态
//ui->pushButtonAdmin->setCheckable(true);
//ui->pushButtonUser->setCheckable(true);
////默认什么都没有选中
//ui->pushButtonAdmin->setChecked(false);
//ui->pushButtonUser->setChecked(false);
//ui->pushButtonAdmin->setStyleSheet(
//          "QPushButton { background-color:green; }"
//          "QPushButton:checked { background-color: red; color: black; }"); // 选中样式
//ui->pushButtonUser->setStyleSheet(
//          "QPushButton { background-color:green; }"
//          "QPushButton:checked { background-color: blue; color: black; }"); // 选中样式

//}


void MainWindow::on_pushButtonLogin_clicked()//登录
{
     LineEditPassword();//重要
    //测试

    openMainInterface();
    qDebug()<<"openMainInterface()";

}


void MainWindow::on_pushButtonCancel_clicked()
{
    ui->lineEdit_Password->clear();
    qDebug()<<"取消登录";
    this->close();
}

void MainWindow::reshowMainWindow()
{
    this->show();
}



void MainWindow::on_pushButtonRegister_clicked()//注册信息
{
    UserInfo user;
   // RegisteredUserInformation *qRView=new RegisteredUserInformation(this);
    //qRView->show();
    RegisteredUserInformation::instance()->show();

}


void MainWindow::on_radioButtonAdmin_clicked()
{
   ui->pushButtonAdmin->setChecked(true);
   userType=true;
}


void MainWindow::on_pushButtonUser_clicked()
{

}


void MainWindow::on_radioButtonUser_clicked()
{
    ui->pushButtonUser->setChecked(true);
    userType=false;
}

void MainWindow::quitSystem()
{
   this->close();
   QApplication::quit();
}


